import Request from './request'
import './index.scss'
import weshare from './weshare'
import Cookies from 'js-cookie'
import html2canvas from "html2canvas";
import { GetQueryString } from 'utils/tools'
//图片
import exchange_shi from '@/imgs/my_chui.png'
import exchange_jian from '@/imgs/my_jiandao.png'
import exchange_bu from '@/imgs/my_bu.png'
import bangPhone from '@/imgs/bangPhone.png'
import guanzhu from '@/imgs/erweima.png'
import bg_record2 from '@/imgs/bg_record2.png'
import bg_record from '@/imgs/bg_record.png'
import num_0 from '@/imgs/num_0.png'
import num_1 from '@/imgs/num_1.png'
import num_2 from '@/imgs/num_2.png'
import num_3 from '@/imgs/num_3.png'
import num_4 from '@/imgs/num_4.png'
import num_5 from '@/imgs/num_5.png'
import num_6 from '@/imgs/num_6.png'
import num_7 from '@/imgs/num_7.png'
import num_8 from '@/imgs/num_8.png'
import num_9 from '@/imgs/num_9.png'
import num_10 from '@/imgs/num_10.png'
// import x1 from '@/imgs/x1.png'
// import x2 from '@/imgs/x2.png'
// import x3 from '@/imgs/x3.png'
// import x4 from '@/imgs/x4.png'
// import x5 from '@/imgs/x5.png'
// import x6 from '@/imgs/x6.png'
import result_ping from '@/imgs/frame_pingju.png'
import result_fail from '@/imgs/frame_chadian.png'
import m100 from '@/imgs/100mb.png'
import m200 from '@/imgs/200mb.png'
import m300 from '@/imgs/300mb.png'
import m400 from '@/imgs/400mb.png'
import m500 from '@/imgs/500mb.png'
import m600 from '@/imgs/600mb.png'
import weiji from '@/imgs/btn_weijih.png'
import yiji from '@/imgs/btn_yijihuo.png'
import yiguo from '@/imgs/btn_yiguoqi.png'
import jihuozhong from '@/imgs/jihuozhong.png'
let numX = [num_0,num_1,num_2,num_3,num_4,num_5,num_6,num_7,num_8,num_9,num_10]
let xb = [m100,m200,m300,m400,m500,m600]
let prizeStatus = [weiji,yiji,yiguo,jihuozhong]
let mobile, userHeadurl,openid,bangwai,nickName;
let scroll//boss出拳滚动定时器
$('.main').height($('body').height())
$('.winListFrame').height($('body').height())
$('.figthListFrame').height($('body').height())
$('.shareQrcodeFrame').height($('body').height())
$('.sendQrcodeFrame').height($('body').height())
$('.realShareFrame').height($('body').height())
$('.userFrame').height($('body').height())
$('.resultShade').height($('body').height())
$('.rulemop').height($('body').height())
//出拳
function fightAgainst(types,_this,_thisToo){
    if(Cookies.get('health')>0){
        clearInterval(scroll)       
        let exchange = [exchange_jian,exchange_shi,exchange_bu]
        if(Cookies.get('jsb')==1){
            $('#shear').show()
            $('#shearToo').css('animation','')
            $('#shearToo').hide()
        }else if(Cookies.get('jsb')==2){
            $('#stone').show()
            $('#stoneToo').css('animation','')
            $('#stoneToo').hide()
        }else if(Cookies.get('jsb')==3){
            $('#cloth').show()
            $('#clothToo').css('animation','')
            $('#clothToo').hide()
        }
        $('.bigLeft').css({ "background": "url("+ exchange[types-1] + ")", 'backgroundSize': '100% 100%' })
        _this.hide()
        $('#'+_thisToo+'').show().css('animation','scale 1.5s linear infinite')
        $('.againTip').show()
        Cookies.set('jsb',types)
        //boss拳头滚动
        let excNum = 0
        scroll=setInterval(function(){
            excNum += 1 
            if(excNum==3){
                excNum=0
            }
            $('.bigRight').css({ "background": "url("+ exchange[excNum] + ")", 'backgroundSize': '100% 100%' })
        },200)
        //再次出拳
        $('#'+_thisToo+'').off('click').on('click',function(){
            //不允许出拳
            $('#noFight').show()
            $('.againTip').hide()
            Cookies.remove('jsb')
            _this.show()
            $('#'+_thisToo+'').hide()
            //滚动
            $.ajax({
                    type: "post",
                    url: Request + '/fightAgainst.do',
                    data: { 'phoneNum': mobile,fightAgainst:types },
                    dataType: "json",
                    success: data => {
                            //不允许出拳关闭
                            $('#noFight').hide()
                            clearInterval(scroll)                    
                            if (data.resCode == 0) {
                                Cookies.set('health',data.retMsg.physicalValue)
                                $('.bigRight').css({ "background": "url("+ exchange[data.retMsg.boss-1] + ")", 'backgroundSize': '100% 100%' })
                                $('.heart i').css({ "background": "url(" + numX[data.retMsg.physicalValue] + ")", 'backgroundSize': '100% 100%' })
                                $('.prize').css({ "background": "url(" + xb[data.retMsg.beishu-1] + ")", 'backgroundSize': '100% 100%' })
                                if(data.retMsg.vsreuslt==1){//平
                                    $('.resultShade .resultFrame').css({ "background": "url("+ result_ping + ")", 'backgroundSize': '100% 100%' })
                                }else if(data.retMsg.vsreuslt==2){//负
                                    $('.resultShade .resultFrame').css({ "background": "url("+ result_fail + ")", 'backgroundSize': '100% 100%' })
                                }
                                setTimeout(()=>{
                                    if(data.retMsg.vsreuslt==0){//胜利
                                        $('.realShareFrame').show();
                                        $('.realShareFrame .myChou .redPink').text(data.faceValue+'MB')    
                                        $('.sendQrcodeFrame').show();
                                        $('.congratulation').html(data.resultString)
                                        if(data.retMsg.user == 'new'){
                                            $('.sendQrcodeFrame .QrcodeFrameText').text('长按二维码发送给新用户激活奖励吧~')
                                            $('#publicity').text('邀请扫码成功可获得鲁信影城25元优惠观影券1张')
                                        }else{
                                            $('.sendQrcodeFrame .QrcodeFrameText').text('长按二维码发送给好友激活奖励吧~')
                                            $('#publicity').text('邀请新用户扫码可获得鲁信影城25元优惠观影券1张')
                                        }
                                        document.getElementById("sendShade").src=''
                                        $('.sendQrcodeFrame .shareCode').attr('src','https://wx.online-cmcc.cn/shandong/wx/proxy/showqrcode/' + data.retMsg.ticket);
                                        $('.realShareFrame .shareCode').attr('src','https://wx.online-cmcc.cn/shandong/wx/proxy/showqrcode/' + data.retMsg.ticket);
                                        html2canvas(document.getElementsByClassName("realShareFrame")[0],{useCORS: true}).then(function(canvas) {
                                            document.getElementById("sendShade").src = canvas.toDataURL("image/png");
                                        });
                                    }else{
                                        $('.resultShade').show()
                                        $('#resultText').html(data.resultString)
                                    }                                    
                                },1000)   
                                //倒计时
                                $('.time30').show()
                                let now30 = new Date().getTime() + 60000
                                let now = new Date().getTime()
                                let expireMin = (now30 - now) / 1000
                                let expireTime = setInterval(function () {
                                    expireMin = expireMin - 1;
                                    if (expireMin > 0) {
                                        let minute = parseInt(expireMin / 60);
                                        let second = parseInt(expireMin % 60);
                                        if (minute < 10) {
                                            minute = '0' + minute
                                        }
                                        if (second < 10) {
                                            second = '0' + second
                                        }
                                        $('.time30 dd').text('00:' + minute + ':' + second)
                                    } else {
                                        $('.time30').hide()
                                        Cookies.remove('fightTime')
                                        clearInterval(expireTime)
                                    }
                                }, 1000);
                                Cookies.set('fightTime', now30)
                            }else{
                                $('.comText').show()
                                $('#comText').text(data.resultString)
                            }
                    }
                });
        })
    }else{
        $('.comText').show()
        $('#comText').html('<span class="jiaTip"></span>目前体力不足了</br>点击首页左上角“+”可以增加体力哦~')
    }
    
}

function init(){
    $.ajax({
        type: "post",
        url: Request + '/rockPaperScissorsCenter.do',
        data: { 'phoneNum': mobile ,'openid':openid},
        dataType: "json",
        success: data => {
            if (data.resCode == 0) {
                if(data.retMsg.timeOut){
                    $('.time30').show().html("游戏已结束");
                    $('.time30').css({"font-size":".6rem","line-height":"1.77rem"})
                }
                Cookies.set('health',data.retMsg.physicalValue)
                $('.heart i').css({ "background": "url(" + numX[data.retMsg.physicalValue] + ")", 'backgroundSize': '100% 100%' })
                $('.prize').css({ "background": "url(" + xb[data.retMsg.beishu-1] + ")", 'backgroundSize': '100% 100%' })
                $('.shareQrcodeFrame .shareCode').attr('src','https://wx.online-cmcc.cn/shandong/wx/proxy/showqrcode/' + data.retMsg.ticket);
                //出拳
                $('#stone').on('click',function(){
                    fightAgainst(2,$(this),'stoneToo')
                })
                $('#shear').on('click',function(){
                    fightAgainst(1,$(this),'shearToo')
                })
                $('#cloth').on('click',function(){
                    fightAgainst(3,$(this),'clothToo')
                })
                //红点
                if(data.retMsg.red==1){
                    $('#winClick i').show()
                }
                //倒计时还剩多少秒
                let nowDate = new Date().getTime()
                let expireTime = Cookies.get('fightTime')
                let expireMin = ''
                if (expireTime) {
                    if (nowDate >= expireTime) {//如果到了5分钟
                        Cookies.remove('fightTime')
                    } else {
                        let expireMs = expireTime - nowDate
                        expireMin = Math.floor(expireMs / 1000)
                    }
                }
                if (expireMin > 0) {
                    $('.time30').show()
                    let expireInter = setInterval(function () {
                        expireMin = expireMin - 1;
                        if (expireMin > 0) {
                            let minute = parseInt(expireMin / 60);
                            let second = parseInt(expireMin % 60);
                            if (minute < 10) {
                                minute = '0' + minute
                            }
                            if (second < 10) {
                                second = '0' + second
                            }
                            $('.time30 dd').text('00:' + minute + ':' + second)
                        } else {
                            $('.time30').hide()
                            Cookies.remove('fightTime')
                            clearInterval(expireInter)
                        }
                    }, 1000);
                }
            }else{
                $('.comText').show()
                $('#comText').text(data.resultString)
            }
        }
    });
}
//发送二维码关闭
showHide($('.sendQrcodeFrame .frameClose'), $('.sendQrcodeFrame'), 0)
showHide($('.sendQrcodeFrame .frameClose'), $('.realShareFrame'), 0)
//获取用户信息
{
    const isCode = localStorage.getItem('caiquan10086')
    const code = GetQueryString('code')
    localStorage.setItem('caiquan10086', code)
    const ua = navigator.userAgent.toLowerCase();
    if (code && isCode != code) {
        $.ajax({
            type: "post",
            url: Request + '/getUserInfo.do',
            data: { 'code': code },
            dataType: "json",
            success: data => {
                Cookies.remove('isProvinceCode')
                Cookies.remove('isPhoneStatus1')
                Cookies.remove('isPhoneStatus2')
                if (data.resCode == 0) {//关注且绑定
                    mobile = encodeURIComponent(data.retMsg.phone)
                    openid = data.retMsg.openid
                    userHeadurl = data.retMsg.headimgurl
                    nickName = data.retMsg.nickname
                    $('.nikeName').text(nickName)
                    localStorage.setItem('caiquanMobile10086', mobile)
                    localStorage.setItem('caiquanHead10086', userHeadurl)
                    localStorage.setItem('caiquanName10086', nickName)
                    init()
                    iframeBrush(mobile,'wechat','fight')
                    //分享
                    weshare('https://wx.online-cmcc.cn/shandong/wx/fight/index.html',numX,Request,xb)
                } else if (data.resCode == 2) {//关注没绑
                    Cookies.set('isPhoneStatus1', '1')
                    $('.userFrame').show()
                    $('.userFrame .userFrameText').text('请您先绑定手机号！')
                    $('.userFrame .shareCode').attr('src', bangPhone)
                } else if (data.resCode == 3) {//未关注
                    Cookies.set('isPhoneStatus2', '1')
                    $('.userFrame .userFrameText').text('请您关注微信公众号！')
                    $('.userFrame').show()
                    $('.userFrame .shareCode').attr('src', guanzhu)
                } else if (data.resCode == 4) {//外省
                    Cookies.set('isProvinceCode', '1')
                    $('.userFrame').show()
                    $('.userFrame .userFrameText').text('非山东移动用户不可参加')
                    $('.userFrame .shareCode').attr('src', guanzhu)
                } else {
                    $('.comText').show()
                    $('#comText').text(data.resultString)
                }
            }
        });
    } else {
          location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx43a850f87498127d&redirect_uri=https%3A%2F%2Fwx.online-cmcc.cn%2Fshandong%2Fwx%2Ffight%2Findex.html%3fFromOpenid%3d%26appType%3d1"+"&response_type=code&scope=snsapi_base&state=123&connect_redirect=1&jsoncallback=?#wechat_redirect";
            
          // if (Cookies.get('isProvinceCode')) {
            //     $('.userFrame').show()
            //     $('.userFrame .userFrameText').text('非山东移动用户不可参加')
            //     $('.userFrame .shareCode').attr('src', guanzhu)
            // }
            // if (Cookies.get('isPhoneStatus1')) {
            //     $('.userFrame').show()
            //     $('.userFrame .userFrameText').text('请您先绑定手机号！')
            //     $('.userFrame .shareCode').attr('src', bangPhone)
            // }
            // if (Cookies.get('isPhoneStatus2')) {
            //     $('.userFrame .userFrameText').text('请您关注微信公众号！')
            //     $('.userFrame').show()
            //     $('.userFrame .shareCode').attr('src', guanzhu)
            // }
            // mobile = localStorage.getItem('caiquanMobile10086')
            // if (mobile) {
            //     iframeBrush(mobile,'wechat','fight')
            //     init()           
            //     $('.nikeName').text(localStorage.getItem('caiquanName10086'))
            // }

    }
   
    // mobile = 'EF6FC860A94AA03D8706010D0F7ECFA4'
    // init()
}

//机器人随机头像
// let bossHead = [boss1, boss2, boss3, boss4, boss5, boss6]
// let bossHeadRandom = bossHead[Math.floor(Math.random() * 6)] 
// $('.robotHead').css({ "background": "url(" + bossHeadRandom + ")", 'backgroundSize': '100% 100%' })
// $('.vs').css({ "background": "url(" + bossHeadRandom + ")", 'backgroundSize': '100% 100%' })

//引导
if (localStorage.getItem('guide') !== '20181112') {
    localStorage.setItem('guide', '20181112')
    $('.guide').show()
}

//进入提示
// if (localStorage.getItem('chuanglian') !== '20181211') {
//     localStorage.setItem('chuanglian', '20181211')
//     $('.comText').show()
//     // $('#comText').html(`<span class="tip">小提示</span><br>本活动将于2018年12月27日结束，请及时激活卡券~`)
//     $('#comText').html(`<span class="tip">小提示</span><br>邀请新用户扫码成功，即可获得鲁信影城25元优惠观影券1张~`)
// }

//窗帘
if (localStorage.getItem('chuanglian') !== '20181226') {
    localStorage.setItem('chuanglian', '20181226')
    $('.pptvmop').show()
    $('.pptvmop .close').on('click',function(){
        $('.pptvmop').hide()
    })
}

//打开关闭
function showHide(click, who, type) {
    if (type == 1) {//显示
        click.on('click', () => {
            who.show()
        })
    } else {//隐藏
        click.on('click', () => {
            who.hide()
        })
    }
}

//分享引导
$('.heart p').on('click',function(){
    $('.shareQrcodeFrame').show()
        html2canvas(document.getElementsByClassName("shareQrcodeFrame")[0],{useCORS: true}).then(function(canvas) {
            console.log(canvas)
            document.getElementById("shareShade").src = canvas.toDataURL("image/png");
        });
})
showHide($('.shareQrcodeFrame .frameClose'), $('.shareQrcodeFrame'), 0)
//引导关闭
showHide($('.guide .guideClose'), $('.guide'), 0)
//结果关闭
showHide($('.resultShade .frameClose'), $('.resultShade'), 0)
//中奖记录
$('#winClick').on('click', () => {
    $('.winListFrame').show()
    $.ajax({
        type: "post",
        url: Request + '/winningRecord.do',
        data: { 'phoneNum': mobile },
        dataType: "json",
        success: data => {
            if (data.resCode == 0) {
                $('.winListFrame .winBox').empty()
               $.each(data.retMsg.list,  (i, e) => { 
                    let str = `<div class="winBlock">
                    <div class="myCoupon">${e.name}</div>
                    <div class="winStatus" id="prize${e.id}" style="background:url(${prizeStatus[e.status]});" data-prize="${e.type}"></div>
                    <div class="winDate">激活有效期至${e.effectiveDate}</div>   
                    </div>`
                    $('.winListFrame .winBox').append(str)
                    $('.winListFrame .winBox .winStatus').css('backgroundSize','100% 100%')
                    if(e.status == 0){
                        $('#prize'+e.id).on('click',function(){
                            let prize = $(this).attr('data-prize');
                            $.ajax({
                                type: "post",
                                url: Request + '/activationCard.do',
                                data: { 'phoneNum': mobile ,'id':e.id},
                                dataType: "json",
                                success: data => {
                                    if (data.resCode == 0) {
                                        $('.winListFrame').hide()
                                        $('.congratulation').text('扫码助我得奖励')
                                        $('.sendQrcodeFrame').show()
                                        $('.realShareFrame').show()         
                                        $('.realShareFrame .myChou .redPink').text(prize+'MB')              
                                        if(data.retMsg.user == 'new'){
                                            $('.sendQrcodeFrame .QrcodeFrameText').text('长按二维码发送给新用户激活奖励吧~')
                                            $('#publicity').text('邀请扫码成功可获得鲁信影城25元优惠观影券1张')
                                        }else{
                                            $('.sendQrcodeFrame .QrcodeFrameText').text('长按二维码发送给好友激活奖励吧~')
                                            $('#publicity').text('邀请新用户扫码可获得鲁信影城25元优惠观影券1张')
                                        }
                                        document.getElementById("sendShade").src=''
                                        html2canvas(document.getElementsByClassName("realShareFrame")[0],{taintTest:false,useCORS:true,allowTaint:false}).then(function(canvas) {
                                            document.getElementById("sendShade").src = canvas.toDataURL("image/png");
                                        });
                                        $('.realShareFrame .shareCode').attr('src','https://wx.online-cmcc.cn/shandong/wx/proxy/showqrcode/' + data.retMsg.ticket);
                                        $('.sendQrcodeFrame .shareCode').attr('src','https://wx.online-cmcc.cn/shandong/wx/proxy/showqrcode/' + data.retMsg.ticket);
                                    }else{
                                        $('.winListFrame').hide()
                                        $('.comText').show()
                                        $('#comText').text(data.resultString)
                                    }
                                }
                            });
                        })
                    }else if(e.status == 3){
                        $('#prize'+e.id).on('click',function(){
                            $('.comText').show()
                            $('#comText').text('卡券正在激活,将于72小时内发放至卡券中心')
                        })
                    }else if(e.status == 1){
                        $('#prize'+e.id).next().html(`卡券已于${e.activationDate.slice(0,11)}激活`)
                    }
                });
            } else {
                $('.winListFrame').hide()
                $('.comText').show()
                $('#comText').text(data.resultString)
            }
        }
    });
})
showHide($('.winListFrameClose'), $('.winListFrame'), 0)
//对战纪录
$('#fightClick').on('click', () => {
    $('.figthListFrame').show()
    $.ajax({
        type: "post",
        url: Request + '/warRecord.do',
        data: { 'phoneNum': mobile },
        dataType: "json",
        success: data => {
            if (data.resCode == 0) {
                $('.fightBox').empty()
                $('#rank').empty()
                //对战纪录
                let str = ''
                $.each(data.list, (i, e) => {
                    let date = e.date.slice(0, 11)
                    if (i == 0) {
                        str += `<div class="hisDate">${date}</div>`
                    } else {
                        if (date!=data.list[i-1].date.slice(0, 11)) {
                            str += `<div class="hisDate">${date}</div>`
                        }
                    }
                    //剪刀石头布
                    let fightme, lightyou, result
                    if (e.woPunches == 1) {
                        fightme = 'fightjian'
                    } else if (e.woPunches == 2) {
                        fightme = 'fightchui'
                    } else if (e.woPunches == 3) {
                        fightme = 'fightbu'
                    }
                    if (e.bassPunches == 1) {
                        lightyou = 'fightjian'
                    } else if (e.bassPunches == 2) {
                        lightyou = 'fightchui'
                    } else if (e.bassPunches == 3) {
                        lightyou = 'fightbu'
                    }
                    if (e.vsResult == 0) {
                        result = 'fightwin'
                    } else if (e.vsResult == 1) {
                        result = 'fightping'
                    } else if (e.vsResult == 2) {
                        result = 'fightfail'
                    }
                    str += `
                        <div class="winBlock">
                        <span><div class="fightme ${fightme}"><div class="fightvs"></div></div></span>
                        <span><div class="fightyou ${lightyou}"></div></span>
                        <span><div class="fightResult ${result}"></div></span>
                    </div>`
                });
                $('.fightBox').append(str)
                //排行榜
                let rankStr=''
                $.each(data.retMsg.list, function (i, e) { 
                     rankStr +=  `<li>
                     <span class="mingci">${e.ranking}</span>
                     <span class="userId">${e.phoneNum}</span>
                     <span class="saoma">${e.count}</span>
                   </li>`
                });
                $('#rank').append(rankStr)
                //榜内
                if(Number(data.personlist[0].ranking<=10)){
                   bangwai = true;
                   $('#rank li:nth-of-type('+data.personlist[0].ranking+') span').css({'color':'#FF175F','font-size':'.35rem'})
                }
                //个人
                $('#bangwai .mingci').text("1")
                $('#bangwai .userId').text(data.personlist[0].phoneNum)
                $('#bangwai .saoma').text(data.personlist[0].count)
            } else {
                $('.figthListFrame').hide()
                $('.comText').show()
                $('#comText').text(data.resultString)
            }
        }
    });
})

showHide($('.figthFrameClose'), $('.figthListFrame'), 0)
showHide($('.rulemop .close'), $('.rulemop'), 0)
//通用弹窗关闭
showHide($('.comText .frameClose'), $('.comText'), 0)

//规则
$('#rule').on('click',function(){
    let url = rule('https://www.shandong10086.com/sdCmosService/activitySupport/preview.do?id=27',3,'fight',0);
    $('.rulemop').show();
    $('#ruleUrl').load(url)
})
//拳王战力榜
$('.myRank').on('click',function(){
    $('.headBlock').hide();
    $('.fightBox').hide();
    $('.rankTime').show();
    $('#rank').show();
    if(!bangwai){
        $('#bangwai').show();
    }   
    $('.figthListFrame .figthListBox').css({ "background": "url("+ bg_record2 + ")", 'backgroundSize': '100% 100%' })
})
//我的记录
$('.myRecord').on('click',function(){
    $('.headBlock').show();
    $('.fightBox').show();
    $('.rankTime').hide();
    $('#rank').hide();
    $('#bangwai').hide();
    $('.figthListFrame .figthListBox').css({ "background": "url("+ bg_record + ")", 'backgroundSize': '100% 100%' })
})
